﻿using FarmSmartSleep.Common.Domain.RBACFile;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace R.FarmSmartSleep.RBAC.API.Apliction.Command
{
    public class EmployeeUpdateHander : IRequestHandler<EmployeeUpdateCommand, Result>
    {

        private readonly IBaseRepository<Employee> employeeRepository;
        private readonly ILogger<EmployeeUpdateHander> logger;
        public EmployeeUpdateHander(IBaseRepository<Employee> employeeRepository, ILogger<EmployeeUpdateHander> logger)
        {
            this.employeeRepository = employeeRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 修改个人用户名信息（只能修改一次）
        /// </summary>
        /// <param name="request">修改个人用户名信息请求对象</param>
        /// <param name="cancellationToken"></param>
        /// <returns>修改个人用户名信息响应对象</returns>
        public async Task<Result> Handle(EmployeeUpdateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result();
                var info = employeeRepository.GetAll().FirstOrDefault(c => c.EmployeeId == request.EmployeeId);
                if (info != null)
                {
                    if (info.UpdateId == 0)
                    {
                        info.Account = request.Account;
                        info.UpdateId = request.EmployeeId;
                        info.UpdateTime = DateTime.Now;
                        result.Code = employeeRepository.Update(info);
                    }
                    else
                    {
                        result.Code = -1;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("用户信息修改方法调用时出错" + ex);
                throw;
            }
        }
    }
}
